﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;

public class AccTestScript : MonoBehaviour
{
    Queue<float> accQueue = new Queue<float>();
    float gForce = 0.98f;

    bool isSfxPlayed = false;

    AudioClip[] clips;
    int[] clipsRatio = new int[] { 3, 3, 3, 3, 1, 1 };

    void Start()
    {
        var audioSource = GetComponent<AudioSource>();
        if (audioSource != null)
        {
            clips = new AudioClip[6];
            for (int i=0; i<clips.Length; i++) clips[i] = Resources.Load<AudioClip>("SFX/NGJ" + i);
        }
    }

    void Update()
    {
        accQueue.Enqueue(Vector3.Distance(Input.acceleration, new Vector3(0.0f, 0.0f, 0.0f)) - gForce);
        if (accQueue.Count > 5) accQueue.Dequeue();

        bool isActionTriggered = (accQueue.Max() >= gForce * 4.0f);
        if (isActionTriggered && !isSfxPlayed)
        {
            var audioSource = GetComponent<AudioSource>();
            if (audioSource != null)
            {
                int idx = 0;
                for (int rnd = Random.Range(0, clipsRatio.Sum()); rnd >= clipsRatio[idx]; rnd -= clipsRatio[idx++]);

                audioSource.pitch = Math.Max(1.0f, Math.Min(3.0f, accQueue.Max() / (gForce * 4.0f)));
                audioSource.PlayOneShot(clips[idx]);
            }

            isSfxPlayed = true;
        }

        isSfxPlayed &= isActionTriggered;

        var text = GetComponent<Text>();
        if (text != null) text.text = accQueue.Max().ToString();

        var image = GetComponent<Image>();
        if (image != null) image.enabled = isSfxPlayed;
    }
}
